// ws instance
let connection;
let userId = null; // 存放当前用户的id用于绑定
// 重连次数上限
const reconnectCountMax = 100;
let reconnectCount = 0;

// 初始化 ws 连接 + 监听
export const initConnection = () => {
    connection?.removeEventListener('message', onConnectGetMsg);
    connection?.removeEventListener('open', onConnectOpen);
    connection?.removeEventListener('close', onConnectClose);
    connection?.removeEventListener('error', onConnectError);
    // console.log('userId',userId);
    // console.log('连接',`ws://localhost:8081/chat${userId ? `?userId=${userId}` : ''}`);
    //ws://localhost:8081/chat?userId=1
    // 建立链接
    // 本地配置到 .env 里面修改。生产配置在 .env.production 里面
    connection = new WebSocket(`ws://localhost:8090`);
    // connection = new WebSocket(`ws://120.26.146.100:10001/chat${userId ? `?userId=${userId}` : ''}`);
    // 收到消息
    connection.addEventListener('message', onConnectGetMsg);
    // 建立链接
    connection.addEventListener('open', onConnectOpen);
    // 关闭连接
    connection.addEventListener('close', onConnectClose);
    // 连接错误
    connection.addEventListener('error', onConnectError);
}

//重连机制
export const onIsConnect = (id) => {
    //判断是否断开连接了
    if (connection == null || connection.readyState !== WebSocket.OPEN) {
        userId = id;
        initConnection();
    }
}

// 发消息给主进程 搭配self.onmessage接受主线程消息
const postMsg = (value) => {
    self.postMessage(value);
}

// 接受到主进程发来的消息
self.onmessage = (e) => {
    console.log("收到主进程发来的消息", e.data)//测试什么内容，每次都报json转换问题
}


//接受到服务端发过来的消息
const onConnectGetMsg = (e) => {
    console.log("连接 接收到消息了", e.data);
    const message = JSON.parse(e.data);
    console.log("服务器发来的消息message", message)
    if (1 === message.type){//返回type=1 成功返回login_url
        // 成功返回login_url
        // 分发自定义事件
        const wxTicketUrlEvent = new CustomEvent('wx-ticket', { detail: message });
        window.dispatchEvent(wxTicketUrlEvent);
    }else if(2 === message.type){
        // 用户等待认证授权
        const waitEvent = new CustomEvent('wx-login-waiting',{detail:message});
        window.dispatchEvent(waitEvent)
    }else if(3 === message.type){
        const successEvent = new CustomEvent('wx-login-success',{detail:message});
        window.dispatchEvent(successEvent)
    }else if(4 === message.type){
        const emailSuccessEvent = new CustomEvent('wx-login-success-email',{detail:message});
        window.dispatchEvent(emailSuccessEvent)
    }
}

//连接成功后触发该方法
//（window.addEventListener自定义的）
const onConnectOpen = (e) => {
    console.log("连接成功的触发open被调用", e.data);
    //链接成功后 请求服务器返回微信二维码消息
    connectionSendWxTicketUrl();
}

//相当于连接关闭(感知到连接关闭)
const onConnectClose = (e) => {
    // postMsg({ type: 'close' });
    postMsg('close');
    console.log("连接关闭的触发close被调用", e.data);
    connection?.close();
    //连接关闭发送一个消息type=1表示需要解绑，uid-channel （关闭好像不能发送？）
    //connection?.send(JSON.stringify({type: 1,value:userStoreAPI.getCurrentUser().id}))
}

// ws 连接 error 连接失败触发该方法
const onConnectError = () => {
    // onCloseHandler()
    // postMsg({ type: 'error' });
    postMsg('error');
    //todo 尝试重新连接
    console.log("连接失败的触发error被调用");
}

// 往 ws 发消息 绑定  (这里不需要了)
//过期
// export const connectionSendBind = (uid:any) => {
//     console.log('uid',uid);
//     const object = {type:0,uid:uid};
//     connection?.send(JSON.stringify(object));
// }

//发送 申请 微信登录二维码Url
export const connectionSendWxTicketUrl = async () => {
    const object = { type: 1 };
    //todo 校验是否断开，断开则重新连接
    if (connection != null && connection.readyState === WebSocket.OPEN) {
        connection?.send(JSON.stringify(object));
    } else {
        await initConnection();
        connection?.send(JSON.stringify(object));
    }
}

//发送回复好友申请消息
export const connectionSendAddApplyRes = async (uid, content, toUid, fromName, toName) => {
    const object = { "type": 3, "uid": uid, "content": content, "toUid": toUid, "fromName": fromName, "toName": toName };
    //todo 校验是否断开，断开则重新连接
    console.log("connection", connection)
    if (connection != null && connection.readyState === WebSocket.OPEN) {
        connection?.send(JSON.stringify(object));
    } else {
        userId = uid;
        await initConnection();
        connection?.send(JSON.stringify(object));
    }
}

//发送私聊消息
export const connectionSendFriendChat = async (uid, content, toUid) => {
    const object = { type: 4, uid: uid, content: content, toUid: toUid };
    //todo 校验是否断开，断开则重新连接
    if (connection != null && connection.readyState === WebSocket.OPEN) {
        connection?.send(JSON.stringify(object));
    } else {
        userId = uid;
        await initConnection();
        connection?.send(JSON.stringify(object));
    }
}

//发送群聊消息
export const connectionSendTeamChat = async (uid, content, teamId) => {
    const object = { type: 5, uid: uid, content: content, teamId: teamId };
    //todo 校验是否断开，断开则重新连接
    if (connection != null && connection.readyState === WebSocket.OPEN) {
        connection?.send(JSON.stringify(object));
    } else {
        userId = uid;
        await initConnection();
        connection?.send(JSON.stringify(object));
    }
}

//发送私聊表情包
export const connectionSendFriendChatEmoji = async (uid, content, toUid) => {
    const object = { type: 6, uid: uid, content: content, toUid: toUid };
    if (connection != null && connection.readyState === WebSocket.OPEN) {
        connection?.send(JSON.stringify(object));
    } else {
        userId = uid;
        await initConnection();
        connection?.send(JSON.stringify(object));
    }
}

//发送群聊消息
export const connectionSendTeamChatEmoji = async (uid, content, teamId) => {
    const object = { type: 7, uid: uid, content: content, teamId: teamId };
    if (connection != null && connection.readyState === WebSocket.OPEN) {
        connection?.send(JSON.stringify(object));
    } else {
        userId = uid;
        await initConnection();
        connection?.send(JSON.stringify(object));
    }
}

